import os

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from .config import Config

db = SQLAlchemy()


def create_app():
    app = Flask(
        __name__,
        instance_relative_config=True,
        static_folder='../static',  # ← 指向项目根的 static/
        static_url_path='/static',  # ← URL 前缀
        template_folder='../templates'  # ← 如果 templates 也在根目录
    )
    app.secret_key = 'your_secret_key'
    app.config.from_object(Config)
    db.init_app(app)

    # 注册蓝图
    from .auth import auth_bp
    app.register_blueprint(auth_bp)
    from .main import main_bp
    app.register_blueprint(main_bp)
    from .user_mgmt import user_mgmt_bp
    app.register_blueprint(user_mgmt_bp)
    from .course_mgmt import course_bp
    app.register_blueprint(course_bp)
    from .school_mgmt import bp as school_mgmt_bp
    app.register_blueprint(school_mgmt_bp)
    from .grade_mgmt import bp as grade_mgmt_bp
    app.register_blueprint(grade_mgmt_bp)
    from .password_mgmt import password_bp
    app.register_blueprint(password_bp)
    from .schedule_mgmt import bp as schedule_mgmt_bp
    app.register_blueprint(schedule_mgmt_bp)
    from .schedule_search import search_bp
    app.register_blueprint(search_bp)
    from .schedule_free import free_bp
    app.register_blueprint(free_bp)
    from .schedule_stats import stats_bp
    app.register_blueprint(stats_bp)

    # 确保 instance 目录存在
    try:
        open(app.instance_path + '/.keep', 'a').close()
    except OSError:
        os.makedirs(app.instance_path)

    # 创建数据库
    with app.app_context():
        db.create_all()
        # —— 初始化管理员账号（永不过期+管理员权限） ——

        from .models import User
        admin_name = 'admin'
        admin_pwd = 'admin123'
        if not User.query.filter_by(username=admin_name).first():
            admin = User(username=admin_name, is_admin=True,  is_active=True)
            admin.set_password(admin_pwd)
            db.session.add(admin)
            db.session.commit()
    return app
